using System.Collections.Generic;

namespace Ioc.Kernel.Resolvers
{
    public class Resolver : IResolver
    {
        private readonly IDictionary<ContainerKey, ComponentModel> components;

        /// <summary>
        /// Initializes a new instance of the <see cref="Resolver"/> class.
        /// </summary>
        /// <param name="components">The components.</param>
        public Resolver(IDictionary<ContainerKey, ComponentModel> components)
        {
            this.components = components;
        }

        /// <summary>
        /// Instanciates the specified component.
        /// </summary>
        /// <param name="component">The component.</param>
        /// <returns></returns>
        public object Instanciate(ComponentModel component)
        {
            CreateExpression(component);
            return component.CreateComponent();
        }

        /// <summary>
        /// Creates the expression.
        /// </summary>
        /// <param name="component">The component.</param>
        public void CreateExpression(ComponentModel component)
        {
            if (component.ConstructorCandidate == null)
            {
                component.GenerateConstructor(components);

                foreach (var dependency in component.Dependencies)
                {
                    CreateExpression(dependency.Value);
                }
            }
        }

    }
}